# coding:UTF-8
import time

import network
from machine import Pin, deepsleep

# 配置WiFi参数（需用户修改部分）
WIFI_SSID = 'tp_lwb'
WIFI_PASSWORD = '12345678'
LED_PIN = 2  # 板载LED引脚


def _handle_failure():
    print("达到最大重试次数，进入深度睡眠...")
    deepsleep(10000)  # 10秒后唤醒重试


class Sta:
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.led = Pin(LED_PIN, Pin.OUT)
        self.retry_count = 0
        self.max_retries = 5

    def connect(self):
        # 激活WiFi接口
        self.wlan.active(True)

        # 如果已连接则断开
        if self.wlan.isconnected():
            self.wlan.disconnect()

        # 开始连接
        self.wlan.connect(WIFI_SSID, WIFI_PASSWORD)

        # 等待连接建立（带LED闪烁提示）
        start_time = time.time()
        while not self.wlan.isconnected():
            self.led.value(not self.led.value())
            time.sleep(0.5)
            if time.time() - start_time > 15:  # 15秒超时
                self.retry_count += 1
                if self.retry_count >= self.max_retries:
                    _handle_failure()
                return self.connect()  # 自动重试

        # 连接成功处理
        self.led.value(1)
        print(f"连接成功！IP地址：{self.wlan.ifconfig()[0]}")
        return True


def init_sta():
    # 使用示例
    wifi = Sta()
    wifi.connect()
